//
//  BillingTableViewController.m
//  WWXELuShang
//
//  Created by 王涛 on 15/12/18.
//  Copyright © 2015年 lanou. All rights reserved.
//

#import "BillingTableViewController.h"
#import "BilingHeadView.h"
#import "CalculaterView.h"
#import "CostTableViewCell.h"
#import "CostModel.h"
@interface BillingTableViewController ()
@property (nonatomic, strong) BilingHeadView *billingHeadView;
@property (nonatomic, strong) CalculaterView *calculateView;
@property (nonatomic, strong) NSMutableArray *costModelArray;
@end

@implementation BillingTableViewController

- (NSMutableArray *)costModelArray {
    if (!_costModelArray) {
        _costModelArray = [[NSMutableArray alloc] init];
    }
    return _costModelArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = kBackGroundColor;
    self.calculateView = [[CalculaterView alloc] initWithFrame:(CGRectMake(0, kHeight, kWidth, kHeight / 1.6))];
    self.calculateView.hidden = YES;
    [self.view addSubview:self.calculateView];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    UIButton *button = (UIButton *)[self.calculateView viewWithTag:44];
    [button addTarget:self action:@selector(missCal) forControlEvents:(UIControlEventTouchUpInside)];
    //创建数据库
    [[CostDataBase sharedCost] createSqliteTableWithName:@"费用"];
    [self.tableView registerClass:[CostTableViewCell class] forCellReuseIdentifier:@"costCell"];
    
    self.costModelArray = [[CostDataBase sharedCost] selectAllModel];
    
}

- (void)missCal {
    CAAnimationGroup *group = [CAAnimationGroup animation];
    CABasicAnimation *move = [CABasicAnimation animationWithKeyPath:@"position.y"];
    CGPoint position = self.calculateView.layer.position;
    move.fromValue = [NSNumber numberWithFloat:self.calculateView.layer.position.y];
    move.toValue = [NSNumber numberWithFloat:self.calculateView.layer.position.y + kHeight / 1.6];
    move.duration = 0.2;
    group.animations = @[move];
    group.duration = 0.2;
    [self.calculateView.layer addAnimation:group forKey:@"计算器消失"];
    [self.calculateView bringSubviewToFront:self.billingHeadView.buttonView];
    self.calculateView.layer.position = CGPointMake(position.x, position.y + kHeight / 1.6);
    self.billingHeadView.buttonView.userInteractionEnabled = YES;
    self.tableView.scrollEnabled = YES;
    self.calculateView.hidden = YES;
    self.costModelArray = [[CostDataBase sharedCost] selectAllModel];
    [self.tableView reloadData];
}
- (void)addMoney {
    [self.tableView setContentOffset:(CGPointMake(0, 0)) animated:NO];
    self.tableView.scrollEnabled = NO;
    self.calculateView.hidden = NO;
    CAAnimationGroup *group = [CAAnimationGroup animation];
    CABasicAnimation *move = [CABasicAnimation animationWithKeyPath:@"position.y"];
    CGPoint position = self.calculateView.layer.position;
    move.fromValue = [NSNumber numberWithFloat:self.calculateView.layer.position.y];
    move.toValue = [NSNumber numberWithFloat:self.calculateView.layer.position.y - kHeight / 1.6];
    move.duration = 0.2;
    group.animations = @[move];
    group.duration = 0.2;
    [self.calculateView.layer addAnimation:group forKey:@"计算器出现"];
    self.calculateView.layer.position = CGPointMake(position.x, position.y - kHeight / 1.6);
    self.billingHeadView.buttonView.userInteractionEnabled = NO;
}
- (void)back {
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
#warning Incomplete implementation, return the number of sections
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete implementation, return the number of rows
    return self.costModelArray.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return kHeight / 9;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    CostTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"costCell" forIndexPath:indexPath];
    cell.backgroundColor = kBackGroundColor;
    NSInteger number = self.costModelArray.count - 1;
    cell.costModel = self.costModelArray[number - indexPath.row];
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return kHeight / 3.5 + kHeight / 10;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    self.billingHeadView = [[BilingHeadView alloc] initWithFrame:(CGRectMake(0, 0, kWidth, kHeight / 3.5  + kHeight / 10))];
    self.billingHeadView.backgroundColor = kBackGroundColor;
    NSInteger sum = 0;
    for (int i = 0; i < self.costModelArray.count; i ++) {
        NSInteger money = [[self.costModelArray[i] money] integerValue];
        sum += money;
    }
    self.billingHeadView.moneyLabel.text =[@"¥" stringByAppendingString:[[NSString stringWithFormat:@"%ld",sum] stringByAppendingString:@".00"]];
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeSystem];
    backButton.frame = CGRectMake(kWidth / 25, kHeight / 26.68, kWidth / 12.5, kHeight / 22.23);
    [backButton addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    [backButton setImage:[UIImage imageNamed:@"arrowdown"] forState:UIControlStateNormal];
    [backButton setTintColor:[UIColor whiteColor]];
    [self.billingHeadView addSubview:backButton];
    
    UILabel *label = [[UILabel alloc] initWithFrame:(CGRectMake(kWidth / 6.25, kHeight / 26.68, kWidth - kWidth / 6.25 * 2, kHeight / 22.23))];
    label.font = [UIFont fontWithName:@"Courier-Bold" size:18];
    label.textColor = [UIColor whiteColor];
    label.textAlignment = NSTextAlignmentCenter;
    label.text = @"计费管家";
    [self.billingHeadView addSubview:label];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(addMoney)];
    [self.billingHeadView.buttonView addGestureRecognizer:tap];
    return self.billingHeadView;
}


// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}



// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        CostModel *costModel = [[CostModel alloc] init];
        NSInteger number = self.costModelArray.count - 1;
        costModel = [self.costModelArray objectAtIndex:number - indexPath.row];
        [self.costModelArray removeObjectAtIndex:number - indexPath.row];
        [[CostDataBase sharedCost] deleteWithDate:costModel.date];
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
        [self.tableView reloadData];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }
}


/*
 // Override to support rearranging the table view.
 - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
 }
 */

/*
 // Override to support conditional rearranging of the table view.
 - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the item to be re-orderable.
 return YES;
 }
 */

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
